package com.ztspeech;

import android.support.annotation.NonNull;

import org.dragonnova.meetingapp.utils.LogUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2015/8/5 11:11.
 * Author: Songxy
 * Email: thinkdata@163.com
 */
public abstract class AZTClient {

    private final String TAG = AZTClient.class.getName();

    private static String serverUrl;
    private final static String publicParam = "cs=41029040&un=ztasrcloudtest1";


    protected HttpURLConnection conn = null;

    protected static String gender;
    public static final String GENDER_MALE = "m";
    public static final String GENDER_FEMALE = "f";
    public void setGender(String g) {
        gender = g;
    }

    protected String language;
    public static final String LANGUAGE_ENGLISH = "en";
    public static final String LANGUAGE_MANDARIN = "ch";

    public static void setServerPath(String path) {
        if (path != null) {
            serverUrl = path;
        }
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    protected abstract String formatParam();

    /**
     * 处理返回流
     * @param input
     * @return
     * @throws Exception
     */
    protected abstract Object doResponse(InputStream input) throws Exception;

    protected float speed = 1.0f;
    protected void setSpeed(float spd) {
        speed = spd;
    }

    protected String formatPublicParam() {
        if (gender == null)
            gender = GENDER_MALE;
        return String.format(publicParam);
    }

    /**
     * 暂支持字符串
     * @param output
     * @param obj
     * @throws Exception
     */
    private void doRequest(OutputStream output, Object obj) throws Exception {
        if (obj instanceof String) {
            String objStr = (String) obj;
            output.write(objStr.getBytes("UTF-8"));
        }
        output.flush();
    }

    private void doRequest(OutputStream output, byte[] input, int offset, int inputLength)
            throws Exception {
        output.write(input, offset, inputLength);
        output.flush();
    }

    private HttpURLConnection openPostConnection(URL url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/octet-stream");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setUseCaches(false);
        return conn;
    }

    private Object getResponse(HttpURLConnection conn) throws Exception {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            return doResponse(conn.getInputStream());
        }else {
            throw new Exception("Http Client Response Code: " + responseCode);
        }
    }

    protected String doCommonResponse(@NonNull InputStream input) throws Exception {
        StringBuffer result = null;
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(input, Charset.defaultCharset()));
            result = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                result.append(temp).append("\n");
            }
            if (result.toString().equals(""))
                return "服务端无返回值";
            else
                return result.toString();
        }catch (IOException e) {
            LogUtil.e(TAG, "Read InputStream Error: " + e.getMessage());
        }finally {
            if (input != null) input.close();
        }
        return "识别字符出错";
    }

    /**
     * 提交请求
     * @param input
     * @return
     * @throws Exception
     */
    public Object doPost(Object input) throws Exception {
        try {
            if (serverUrl == null) {
                serverUrl = "http://s2s11.simutalk.com/speechtrans/servlet?";
            }
            URL url = new URL(serverUrl + formatPublicParam() + formatParam());
            conn = openPostConnection(url);
            if (input instanceof String) {
                //Content_Length作为InpuStream的长度问题待定？
                conn.setRequestProperty("Content-Length",
                        String.valueOf(((String) input).getBytes("UTF-8").length));
            }
            conn.connect();
            doRequest(conn.getOutputStream(), input);
            return getResponse(conn);
        }catch (IOException e) {
            throw new Exception("Http Client Error: "+ e.getMessage());
        }finally {
            if (conn != null)
                conn.disconnect();
        }
    }

    /**
     * 提交请求
     * @param input
     * @param offset
     * @param inputLength
     * @return
     * @throws Exception
     */
    protected Object doPost(byte[] input, int offset, int inputLength) throws Exception {
        URL url = new URL(serverUrl+formatPublicParam()+formatParam());
        HttpURLConnection conn = openPostConnection(url);
        conn.setFixedLengthStreamingMode(inputLength);
        conn.setRequestProperty("Content-Length", String.valueOf(inputLength));
        conn.connect();
        doRequest(conn.getOutputStream(), input, offset, inputLength);
        return getResponse(conn);
    }
}
